unit Data;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  DBXpress, SqlExpr, FMTBcd, DB;

const fcNew = 1;
      fcOld = 2;

type
  TDM = class(TDataModule)
    OldDB: TSQLConnection;
    NewDB: TSQLConnection;
    RunSQL: TSQLDataSet;
    procedure DataModuleCreate(Sender: TObject);
    procedure DataModuleDestroy(Sender: TObject);
  private
    { Private declarations }
    TransDesc : TTransactionDesc;
    procedure SetDialect(const Value: integer);
    function GetDialect: integer;
  public
    { Public declarations }
    AutoRepair : Boolean;
    ShowReport : Boolean;
    SQL,S      : TStringList;
    property Dialect : integer read GetDialect write SetDialect;

    procedure ConnectOldDB;
    procedure ConnectNewDB;

    procedure ExecRunSQL;
    function CreateQueryOldDB: TSQLDataSet;
    function CreateQueryNewDB: TSQLDataSet;
    procedure AddToStrings(Cap : String; T : TStrings);
  end;

var
  DM: TDM;

implementation

uses ReportForm;

{$R *.DFM}

{ TDM }

function TDM.CreateQueryOldDB: TSQLDataSet;
begin
  Result:=TSQLDataSet.Create(Self);
  Result.SQLConnection:=OldDB;
  Result.CommandText:='';
end;

function TDM.CreateQueryNewDB: TSQLDataSet;
begin
  Result:=TSQLDataSet.Create(Self);
  Result.SQLConnection:=NewDB;
  Result.CommandText:='';
end;


procedure TDM.ExecRunSQL;
begin
  OldDB.StartTransaction(TransDesc);
  try
    RunSQL.CommandText:=SQL.Text;
    RunSQL.ExecSQL;
    OldDB.Commit(TransDesc);
  except
    OldDB.Rollback(TransDesc);
    raise;
  end;
end;

procedure TDM.DataModuleCreate(Sender: TObject);
begin
  S:=TStringList.Create;
  SQL:=TStringList.Create;
  // define transaction type
  With TransDesc do
  begin
    TransactionID:=1;
    GlobalID:=1;
    IsolationLevel:=xilREADCOMMITTED;
  end;
  Dialect:=1;
end;

procedure TDM.DataModuleDestroy(Sender: TObject);
begin
  OldDB.Connected:=False;
  NewDB.Connected:=False;
  SQL.Free;
  S.Free;
end;

function TDM.GetDialect: integer;
var S : String;
begin
  S:=NewDB.Params.Values['SQLDialect'];
  if S='' then S:='1';
  Result:=StrToInt(S);
end;

procedure TDM.SetDialect(const Value: integer);
begin
  NewDB.Params.Values['SQLDialect']:=IntToStr(Value);
  OldDB.Params.Values['SQLDialect']:=IntToStr(Value);
end;

procedure TDM.AddToStrings(Cap : String; T: TStrings);
begin
  T.Text:='/* '+Cap+' */'#13#10+T.Text+';';
  T.Add('');
  S.AddStrings(T);
end;

procedure TDM.ConnectNewDB;
begin
  try
    NewDB.Open;
  except
    NewDB.LoginPrompt:=True;
    NewDB.Open;
  end;
end;

procedure TDM.ConnectOldDB;
begin
  try
    OldDB.Open;
  except
    OldDB.LoginPrompt:=True;
    OldDB.Open;
  end;
end;

end.
